/*
 * @Description: overLay 相关
 * @Date: 2022-04-13 09:58:49
 * @Author: yeming
 */

import OlOverlay from 'ol/Overlay'
import { fromLonLat, toLonLat } from 'ol/proj.js'

const CSS_TEXT = 'width:100px;background:rgba(0,0,0,0.5);color:white;border-radius:4px;padding:5px 10px;box-sizing: border-box;position:relative;font-size:12px;text-align:center;'

class CustomOverlay {
  constructor(ol2d, hashMap) {
    this.ol2d = ol2d
    this.map2d = ol2d.map2d
    this.hashMap = hashMap
  }

  /**
   * @desc: 添加 popup
   * @param {Number} id
   * @param {Array} latlng
   * @param {String} content dom结构字符串 '<div class="popup-container"><div>名称：-- </div><div>机型：-- </div><div>状态：-- </div><div>高度：-- </div><div>空速：-- </div><div>地速：-- </div></div>'
   * @param {String} cssText 样式
   * @param {Array} offset 窗口偏移量 [x, y]
   */
  addPopupOverlay (id, latlng, content, cssText, offset) {
    id = id && id != '' ? id : 'popupOverlay'
    content = content && content != '' ? content : '描述性文字'

    let popup = document.createElement('div')
    popup.id = id;
    popup.style.cssText = cssText
    popup.innerHTML = content
    popup.style.display = 'block' // 配合删除操作做的特殊处理
    document.body.appendChild(popup)

    let overlay = new OlOverlay({
      element: document.getElementById(id),
      rend3d: true,
      autoPan: false, // 地图边缘是否自动移动地图使overlayer完全显示，true 高速移动偶尔会导致地图抖动
      autoPanMargin: 100,
      positioning: 'bottom-left',
      offset: offset || [5, -5]
    })

    overlay.setPosition(fromLonLat(latlng))
    this.map2d.addOverlay(overlay)
    this.hashMap.set(id, overlay)
  }

  /**
   * @desc: 删除 popup
   * @param {Number} id
   */
  delPopupOverlay (id) {
    let currentOverlay = this.hashMap.get(id)
    if (!currentOverlay) return false

    this.map2d.removeOverlay(currentOverlay)
  }

  /**
   * @desc: 删除所有 popup
   */
  delAllPopupOverlay () {
    for (let value of this.hashMap.values()) {
      this.map2d.removeOverlay(value)
    }
    this.hashMap.clear()
  }

  /**
   * @desc: 更新 popup
   * @param {Number} id
   * @param {Array} latlng
   * @param {String} content
   * @param {String} cssText
   */
  updatePopupOverlay (id, latlng, content, cssText, yaw, hpr) {
    let currentOverlay = this.hashMap.get(id)
    if (!currentOverlay) return false

    let popupElement = currentOverlay.getElement()
    let coordinate = fromLonLat(latlng)
    if (content) popupElement.innerHTML = content
    if (cssText) popupElement.style.cssText = cssText
    if (yaw) popupElement.style.transform = 'rotate(' + yaw + 'deg)'
    currentOverlay.setPosition(coordinate)
  }
}

export default CustomOverlay
